﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using XYAC.Framework.MonitorTireMaterialManual.Context;
using XYAC.Framework.MonitorTireMaterialManual.Entities;
using XYAC.Framework.MonitorTireMaterialManual.Extensions;
using XYAC.Framework.MonitorTireMaterialManual.IServices;
using XYAC.Framework.MonitorTireMaterialManual.LocalData.Context;
using XYAC.Framework.MonitorTireMaterialManual.LocalData.Models;

namespace XYAC.Framework.MonitorTireMaterialManual.Services
{
    public class LocalReportService : ServiceBase<int, CurrentReportContext>, ILocalReportService
    {
        private const string? __RECIVE_FLAG_PLANED = "PLANED";

        public LocalReportService(IOptionsMonitor<AppConfig> appConfig, ILogger<LocalReportService> logger, IServiceProvider provider) : base(appConfig, logger, provider)
        {

        }

        public int Add<TType>(TType data, YB_LOT_INSPECT_Local localInspect) where TType : ReportEntityBase
        {
            int ret = 0;
            var date = this.AppConfig.CurrentValue.GetCurrentProcuceDate();
            try
            {
                using (var reportContext = new CustomReportContext(this.AppConfig, DateOnly.FromDateTime(date)))
                {
                    using (var localContext = this.Provider.GetRequiredService<LocalDataContext>())
                    {

                        using (var reportTrans = reportContext.Database.BeginTransaction())
                        {

                            using (var localTrans = localContext.Database.BeginTransaction())
                            {
                                try
                                {
                                    var inspect = localInspect;
                                    if (data is not PreCheckReport)
                                        inspect = localContext.Set<YB_LOT_INSPECT_Local>().FirstOrDefault(T => T.LJ_ID == localInspect.LJ_ID);
                                    inspect.RECEIVE_FLAG = __RECIVE_FLAG_PLANED;
                                    inspect.RemoteSyncDate = DateTime.Now;
                                    inspect.RemoteSyncState = true;
                                    if (data is not PreCheckReport)
                                        localContext.Update(inspect);
                                    else
                                        localContext.Add(inspect);

                                    int inspectChanged = localContext.SaveChanges();

                                    reportContext.Add(data);
                                    int reportChanged = reportContext.SaveChanges();

                                    if (inspectChanged == 1 && reportChanged == inspectChanged)
                                    {
                                        localTrans.Commit();
                                        reportTrans.Commit();
                                        ret = inspectChanged;
                                    }
                                }
                                catch (Exception ex)
                                {
                                    this.Logger.LogError($"出错了:{ex.Message}", ex);
                                    localTrans.Rollback();
                                    reportTrans.Rollback();
                                }

                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                this.Logger.LogError($"记录报表数据失败:{ex.Message}", ex);
            }
            return ret;
        }

        public object findCheckData(string shift, DateTime datetime)
        {
            using var reportContext = new CustomReportContext(this.AppConfig, DateOnly.FromDateTime(datetime));

            var lST = reportContext.PreCheckReport.AsNoTracking().Where(t => t.Shift == shift
            && t.PlanDate.Date == datetime.Date).ToList();
            if (lST.Count > 0)
                return lST[0];
            else
                return null;
        }

        public bool isCheck(string shift, DateTime datetime)
        {
            using var reportContext = new CustomReportContext(this.AppConfig, DateOnly.FromDateTime(datetime));

            var total = reportContext.PreCheckReport.AsNoTracking().Where(t => t.Shift == shift
            && t.PlanDate.Date == datetime.Date).Count();
            if (total > 0)
                return true;
            return false;
        }
    }
}
